package com.mew.chess.core.game.dyj.game.task;

import com.mew.chess.core.common.handler.ChessPushMessageUtil;
import com.mew.chess.core.game.bjl.game.BjlRoomManager;
import com.mew.chess.core.game.bjl.game.common.BjlBetType;
import com.mew.chess.core.game.bjl.game.core.BjlCardDevice;
import com.mew.chess.core.game.bjl.game.core.BjlGameUtil;
import com.mew.chess.core.game.dyj.game.DyjGameManager;
import com.mew.chess.core.game.dyj.game.DyjRoomManager;
import com.mew.chess.core.game.dyj.game.common.*;
import com.mew.chess.core.game.dyj.game.core.DyjDiceUtil;
import com.mew.chess.core.game.dyj.game.message.PushOpenCardMessage;
import com.mew.common.dc.redis.GameRoomRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Map;

/**开牌阶段
 * @author dylin
 * @create 2021/4/22
 */
@Component
@Slf4j
public class DyjOpenCardTask {
    @Autowired
    private GameRoomRedisService gameRoomRedisService;

    public void openCard(int roomId) {
        DyjRoomManager roomManager =DyjGameManager.getInstance().getController(roomId);
        DyjResultBO dyjResult =roomManager.getDyjResult();
        DyjDiceUtil.rockDice(roomManager.getDyjResult());

        //TODO 控制
        boolean control = gameRoomRedisService.isCapacityControl(roomManager.getGameId(), roomManager.getRoomId());
        if(control){
            log.info("----------------DYJ control-----------------");
            control(roomManager,0);
        }
        PushOpenCardMessage message =roomManager.getPushOpenCardMessage();
        message.setDices(dyjResult.getDices());
        ChessPushMessageUtil.broadcastMessage(roomManager.getOnlineUser().values(), DyjPushCMDMapType.OpenCardMessage.code(),message);
        roomManager.changeLink(DyjLinkType.OpenCard.code(), DyjConstantValue.OPEN_CARD_TIME);
    }
    /**
     * 控制
     * @param roomManager
     * @param time
     */
    private void control(DyjRoomManager roomManager, int time){
        long sysPayment = 0;
        Map<Integer, Long> integerLongMap = DyjDiceUtil.computeRegionBet(roomManager);
        for (Map.Entry<Integer, Long> entry : integerLongMap.entrySet()) {
            //区域玩家赢
            if(roomManager.getDyjResult().getWinList().contains(entry.getKey())) {
                sysPayment -= entry.getValue() * DyjBetType.parse(entry.getKey()).rate()/10;
            }else{
                sysPayment += entry.getValue();
            }
        }
        //系统输 重新随结果
        if(sysPayment < 0 && time < 50){
            roomManager.getDyjResult().clear();
            DyjDiceUtil.rockDice(roomManager.getDyjResult());
            time++;
            control(roomManager,time);
        }
    }
}
